package com.tsing.service.impl;

import com.tsing.common.result.PageResult;
import com.tsing.mapper.ArticleMapper;
import com.tsing.mapper.LoveMapper;
import com.tsing.mapper.SearchMapper;
import com.tsing.mapper.impl.ArticleMapperImpl;
import com.tsing.mapper.impl.LoveMapperImpl;
import com.tsing.mapper.impl.SearchMapperImpl;
import com.tsing.pojo.entity.TlLove;
import com.tsing.pojo.entity.TlPost;
import com.tsing.pojo.entity.TlUser;
import com.tsing.pojo.vo.ArticleDetailsVO;
import com.tsing.service.SearchService;

import java.util.ArrayList;
import java.util.List;

/**
 * @auth 卢孝宇
 * @date 2023/12/14 14:30
 */
public class SearchServiceImpl implements SearchService {

    private SearchMapper searchMapper = new SearchMapperImpl();

    private ArticleMapper articleMapper = new ArticleMapperImpl();

    private LoveMapper loveMapper = new LoveMapperImpl();

    @Override
    public List<TlPost> list(String query) {
        return searchMapper.list(query);
    }

    @Override
    public PageResult<ArticleDetailsVO> postList(String query, Integer page, Integer size,Long userId) {
        PageResult<ArticleDetailsVO> apArticleVOList = new PageResult<>();

        List<ArticleDetailsVO> list = new ArrayList<>();

        List<TlPost> pageResultList = searchMapper.postList(query,page,size);


        Integer count = searchMapper.countPost(query);
        for (TlPost tlPost : pageResultList) {

            ArticleDetailsVO a = new ArticleDetailsVO();

            a.setPostId(tlPost.getPostId());
            a.setImage(tlPost.getImage());
            a.setTitle(tlPost.getTitle());
            a.setLikeCount(tlPost.getLikeCount());
            //根据用户id查找对应的用户数据
            List<TlUser> tlUsers = articleMapper.userList(tlPost.getUserId());
            //获取用户是否点赞
            List<TlLove> tlLove = loveMapper.loveCount(userId,tlPost.getPostId());
            a.setLoveCount((long) tlLove.size());

            for (TlUser tlUser : tlUsers) {
                a.setUserName(tlUser.getUsername());
                a.setUserImage(tlUser.getUserImage());
            }
            list.add(a);

        }
        apArticleVOList.setData(list);
        apArticleVOList.setCode(200);
        apArticleVOList.setSize(size);
        apArticleVOList.setTotal(count);
        apArticleVOList.setCurrentPage(page);
        return apArticleVOList;
    }
}
